package com.fesine.ssh.controller;

import com.alibaba.fastjson.serializer.SerializeConfig;
import com.fesine.ssh.model.Category;
import com.fesine.ssh.model.Product;
import com.fesine.ssh.service.CategoryService;
import com.fesine.ssh.service.ProductService;
import com.fesine.ssh.util.DateUtil;
import com.fesine.ssh.util.GenerateUUID;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

/**
 * Created by Fesine on 2016/2/21.
 */
@Controller
@RequestMapping("/product")
public class ProductController {

    private static final Logger logger = Logger.getLogger(ProductController.class);

    @Autowired
    private ProductService productService;
    @Autowired
    private CategoryService categoryService;

    public static SerializeConfig mapping = new SerializeConfig();
    private String str = "";

    /**
     * 查询所有商品信息
     *
     * @param req
     */
    @RequestMapping("/listAllProduct")
    public void listAllProduct(HttpServletRequest req, PrintWriter writer) {
        List<Product> products = productService.findAll();
        int len = products.size();
        String preStr = "{totalCount:" + len + ",rows:[";
        String cenStr = "";
        int i = 0;
        String douhao = ",";
        for (Product product : products) {
            i++;
            cenStr += "{id:'" + product.getId() + "', " +
                    "prodId:'" + product.getProdId() + "'," +
                    "name:'" + product.getName() + "'," +
                    "descr:'" + product.getDescr() + "'," +
                    "normaPrice:'" + product.getNormaPrice() + "'," +
                    "memberPrice:'" + product.getMemberPrice() + "'," +
                    "pdate:'" + product.getPdate() + "'," +
                    "photo:'" + product.getPhoto() + "'," +
                    "cateId:" + product.getCategory().getCateId() + "," +
                    "cateText:'" + product.getCategory().getText() + "'" +
                    "}";
            if (i < len) {
                cenStr += douhao;
            }
        }
        String endStr = "]}";
        String resultStr = preStr + cenStr + endStr;
        writer.write(resultStr);
    }

    /**
     * 分页查询商品信息./product/listProduct.do
     */
    @RequestMapping("/listProduct")
    public void listProduct(HttpServletRequest request, PrintWriter writer) {
        String startStr = request.getParameter("start");
        String limitStr = request.getParameter("limit");

        List<Product> products = productService.findAll(Integer.parseInt(startStr), Integer.parseInt(limitStr));
        int len = products.size();
        String preStr = "{totalCount:" + productService.findAll().size() + ",rows:[";
        String cenStr = "";
        int i = 0;
        String douhao = ",";
        for (Product product : products) {
            i++;
            cenStr += "{id:'" + product.getId() + "', " +
                    "prodId:'" + product.getProdId() + "'," +
                    "name:'" + product.getName() + "'," +
                    "descr:'" + product.getDescr() + "'," +
                    "normaPrice:'" + product.getNormaPrice() + "'," +
                    "memberPrice:'" + product.getMemberPrice() + "'," +
                    "pdate:'" + product.getPdate() + "'," +
                    "photo:'" + product.getPhoto() + "'," +
                    "cateId:" + product.getCategory().getCateId() + "," +
                    "cateText:'" + product.getCategory().getText() + "'" +
                    "}";
            if (i < len) {
                cenStr += douhao;
            }
        }
        String endStr = "]}";
        String resultStr = preStr + cenStr + endStr;
        writer.write(resultStr);
    }


    /**
     * 添加用户
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/addProduct", method = RequestMethod.POST)
    public void addProduct(@RequestParam MultipartFile photos, HttpServletRequest request, HttpServletResponse
            response, PrintWriter writer) throws IOException {
        String name = request.getParameter("name");
        String cateId = request.getParameter("cateId");
        String memberPrice = request.getParameter("memberPrice");
        String normaPrice = request.getParameter("normaPrice");
        String descr = request.getParameter("descr");

        Product product = new Product();
        product.setId(GenerateUUID.getUUId());
        product.setProdId(GenerateUUID.getProdId());
        product.setName(name);
        product.setMemberPrice(Math.round(Float.parseFloat(memberPrice) * 100) / 100.0);
        product.setNormaPrice(Math.round(Float.parseFloat(normaPrice) * 100) / 100.0);
        product.setDescr(descr);
        Category category = categoryService.findByCateId(Integer.parseInt(cateId));
        product.setCategory(category);
        product.setPdate(new Date());
        if (photos.isEmpty()) {
            System.out.println("文件未上传");
            product.setPhoto("default.jpg");
        } else {
            String fileName = DateUtil.formatDate(new Date(), "yyyyMMddHHmmsssss");
            String root = request.getSession().getServletContext().getRealPath("/");
            String filePath = root + "images/product/";
            String orgFileName = photos.getOriginalFilename();//源文件名
            String fileType = orgFileName.substring(orgFileName.lastIndexOf(".") + 1);
            fileName = "[" + fileType + "]" + fileName + "." + fileType;
            //product.setPhoto(photos.getOriginalFilename());
            product.setPhoto(fileName);
            filePath = filePath + fileName;
            logger.info("------>上传文件路径:" + filePath);
            boolean status = true;
            long startTime = System.currentTimeMillis();   //获取开始时间
            try {
                photos.transferTo(new File(filePath));
                long endTime = System.currentTimeMillis(); //获取结束时间
                logger.info("上传文件共使用时间：" + (endTime - startTime));
            } catch (Exception e) {
                fileName = orgFileName;//失败返回源文件名
                status = false;
                e.printStackTrace();
                writer.write("{success:true, msg:'商品新增失败!'}");
            }
            //如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中
            //String realPath = request.getSession().getServletContext().getRealPath("/images/product");
            //这里不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉，我是看它的源码才知道的
            //photos.transferTo(new File(realPath, photos.getOriginalFilename()));
            //FileUtils.copyInputStreamToFile(photos.getInputStream(), new File(realPath, photos.getOriginalFilename
            // ()));
        }

        /**解决乱码问题*/
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;  charset=UTF-8");

        if (null != productService.add(product)) {
            writer.write("{success:true, msg:'商品新增成功!'}");
        } else {
            writer.write("{success:true, msg:'商品新增失败!'}");
        }
    }

    /**
     * 删除商品product/removeProduct.do
     * 同时删除上传的文件
     */
    @RequestMapping(value = "/removeProduct", method = RequestMethod.POST)
    public void deleteProduct(HttpServletRequest request, PrintWriter writer) {

        String[] prodIds = request.getParameter("prodIds").replaceAll("\"", "").split(",");
        String root = request.getSession().getServletContext().getRealPath("/");
        String filePath = root + "images/product/";
        try {
            //先删除图片，再删除数据
            for (String prodId : prodIds) {
                String photo = productService.findByProdId(prodId).getPhoto();
                //不删除默认图片
                if (!"default.jpg".equals(photo)) {
                    logger.info("---------->删除的文件名：" + photo);
                    File file = new File(filePath + photo);
                    file.delete();
                }
            }
            productService.delete(prodIds);
            writer.write("{success:true,msg:'删除成功!'}");
        } catch (Exception e) {
            writer.write("{success:true,msg:'删除失败!'}");
        }

    }

    /**
     * 修改商品信息product/update_product.do
     */
    @RequestMapping(value = "/updateProduct", method = RequestMethod.POST)
    public void updateProduct(@RequestParam MultipartFile photos, HttpServletRequest request, HttpServletResponse
            response, PrintWriter writer) throws IOException {
        String id = request.getParameter("id");
        String prodId = request.getParameter("prodId");
        String name = request.getParameter("name");
        String cateId = request.getParameter("cateId");
        String memberPrice = request.getParameter("memberPrice");
        String normaPrice = request.getParameter("normaPrice");
        String descr = request.getParameter("descr");
        Product product = productService.findByProdId(prodId);
        if (null != name && !name.equals("")) {
            product.setName(name);
        }
        product.setMemberPrice(Math.round(Float.parseFloat(memberPrice) * 100) / 100.0);
        product.setNormaPrice(Math.round(Float.parseFloat(normaPrice) * 100) / 100.0);
        product.setDescr(descr);
        Category category = categoryService.findByCateId(Integer.parseInt(cateId));
        product.setCategory(category);
        product.setPdate(new Date());
        //需要更改图片
        String fileName = DateUtil.formatDate(new Date(), "yyyyMMddHHmmsssss");
        if (!photos.isEmpty()) {
            String root = request.getSession().getServletContext().getRealPath("/");
            String filePath = root + "images/product/";
            String orgFileName = photos.getOriginalFilename();//源文件名
            String fileType = orgFileName.substring(orgFileName.lastIndexOf(".") + 1);
            fileName = "[" + fileType + "]" + fileName + "." + fileType;
            //product.setPhoto(photos.getOriginalFilename());
            product.setPhoto(fileName);
            filePath = filePath + fileName;
            logger.info("------>上传文件路径:" + filePath);
            boolean status = true;
            long startTime = System.currentTimeMillis();   //获取开始时间
            try {
                photos.transferTo(new File(filePath));
                long endTime = System.currentTimeMillis(); //获取结束时间
                logger.info("上传文件共使用时间：" + (endTime - startTime));
            } catch (Exception e) {
                fileName = orgFileName;//失败返回源文件名
                status = false;
                e.printStackTrace();
                writer.write("{success:false, msg:'商品图片更改失败!'}");
            }
        } else {
            fileName = product.getPhoto();
        }
        /**解决乱码问题*/
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;  charset=UTF-8");
        try {
            productService.update(product);
            logger.info("商品修改成功! 商品ID：" + prodId);
            writer.write("{success:true, msg:'商品修改成功!',photo:'" + fileName + "'}");
        } catch (Exception e) {
            writer.write("{success:false, msg:'商品修改失败!'}");
        }

    }
    /**
     * 修改商品信息product/update_product.do
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public void uploadFile(@RequestParam MultipartFile file, HttpServletRequest request, HttpServletResponse
            response, PrintWriter writer) throws IOException {
        //需要更改文件
        String fileName = DateUtil.formatDate(new Date(), "yyyyMMddHHmmsssss");
        if (!file.isEmpty()) {
            String root = request.getSession().getServletContext().getRealPath("/");
            String filePath = root + "images/product/";
            String orgFileName = file.getOriginalFilename();//源文件名
            String fileType = orgFileName.substring(orgFileName.lastIndexOf(".") + 1);
            fileName = "[" + fileType + "]" + fileName + "." + fileType;
            filePath = filePath + fileName;
            logger.info("------>上传文件路径:" + filePath);
            long startTime = System.currentTimeMillis();   //获取开始时间
            try {
                file.transferTo(new File(filePath));
                long endTime = System.currentTimeMillis(); //获取结束时间
                logger.info("上传文件共使用时间：" + (endTime - startTime));
            } catch (Exception e) {
                fileName = orgFileName;//失败返回源文件名
                e.printStackTrace();
                writer.write("{success:false, msg:'文件上传失败!'}");
            }
        }
        /**解决乱码问题*/
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;  charset=UTF-8");
        try {
            logger.info("文件上传成功! 文件名：" + fileName);
            writer.write("{success:true, msg:'文件上传成功!',文件名:'" + fileName + "'}");
        } catch (Exception e) {
            writer.write("{success:false, msg:'文件上传失败!'}");
        }

    }
}
